﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using RestSharp;
using RestSharp.Authenticators;
using System.Configuration;
using MsForgeReboot.Framework.Entities;
using MsForgeReboot.Framework.TownCrierChannelTools;
using MsForgeReboot.Framework.Interfaces;

namespace MsForgeReboot.Framework.TownCrierChannels {
    [Serializable]
    public class TwitterChannel : IChannel {

        private TwitterChannelSection _settings;
        private RestTransport _transport;
        public Event Source { get; set; }

        public TwitterChannel() : 
            this(new RestClient(), new RestRequest(), "TwitterChannelSection") 
        { }


        /// <summary>
        /// Testing constructor, that allows you to inject RestClient,
        /// RestRequest and a whole section
        /// </summary>
        /// <param name="client">IRestClient implementation</param>
        /// <param name="request">IRestRequest implementation</param>
        /// <param name="section">TwitterChannelSection config section</param>
        public TwitterChannel(IRestClient client, IRestRequest request, TwitterChannelSection section) {
            _settings = section;
            this._transport = new RestTransport(client, request);
        }

        public TwitterChannel(IRestClient client, IRestRequest request, string sectionName)  {
            _settings = ConfigurationManager.GetSection(sectionName) as TwitterChannelSection;
            this._transport = new RestTransport(client, request);
        }

        public DeliveryResult DeliverEvent() {
            //throw new NotImplementedException();
            return this.DeliverEvent(this.Source);
        }

        public DeliveryResult DeliverEvent(Event source) {

            if (source == null)
                throw new ArgumentException("Event must be present in the call", "Event");

            IAuthenticator auth = OAuth1Authenticator.ForProtectedResource(
                                                        _settings.OauthToken.ApiKey, 
                                                        _settings.OauthToken.ApiSecret, 
                                                        _settings.OauthToken.AccessToken,           
                                                        _settings.OauthToken.TokenSecret
                                                        );
            Parameter[] param = FormattingTools.FormatEventForTwitter(source);

            DeliveryResult result = this._transport.Post(_settings.ApiBaseUrl.Value, _settings.ApiPostResource.Value, auth, param);
            result.DeliveryChannel = "Twitter Channel";
            return result;
        }

    }
}
